<template>
  <div>
    <el-input v-model="searchinput"
              class="w-50 m-2"
              size="large"
              placeholder="输入搜索的用户名"
              :suffix-icon="Search"
              style="width:200px" />
    <el-table :data="users"
              stripe
              style="width: 100%">
      <el-table-column prop="username"
                       label="用户名"
                       width="180" />
      <el-table-column label="头像"
                       width="140">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <img :src='scope.row.avatar'
                 style="display:block;width:40px;height:40px;"
                 alt="">
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="introduction"
                       label="个人介绍"
                       width="140" />
      <el-table-column prop="sex"
                       label="性别"
                       width="140">
        <template #default="scope">
          <el-select v-model="scope.row.sex"
                     disabled
                     class="m-2"
                     placeholder="Select"
                     size="large">
            <el-option :key="0"
                       label="男"
                       :value="0"></el-option>
            <el-option :key="1"
                       label="女"
                       :value="1"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="birthday"
                       label="生日"
                       width="140">
        <template #default="scope">
          <el-date-picker v-model="scope.row.birthday"
                          type="date"
                          disabled
                          placeholder="Pick a day" />
        </template>
      </el-table-column>
      <el-table-column fixed="right"
                       label="Operations"
                       width="180">
        <template #default="scope">
          <el-button size="small"
                     @click="handleEdit(scope.row)">Edit</el-button>
          <el-popconfirm title="你确定删除此用户？"
                         @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button size="small"
                         type="danger">Delete</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background
                   style="width:200px;margin:10px auto"
                   layout="prev, pager, next"
                   :page-size="6"
                   v-model:current-page="start"
                   :total="total" />
  </div>

  <el-dialog v-model="dialogTableVisible"
             title="编辑用户">
    <el-form :label-position="labelPosition"
             label-width="100px"
             :model="curedit"
             style="max-width: 460px">
      <el-form-item label="用户名">
        <el-input v-model="curedit.username" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="curedit.password" />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="curedit.sex"
                   placeholder="Activity zone">
          <el-option label="男"
                     :value="0" />
          <el-option label="女"
                     :value="1" />
        </el-select>

      </el-form-item>
      <el-form-item label="生日">
        <el-date-picker v-model="curedit.birthday"
                        type="date"
                        placeholder="Pick a day" />
      </el-form-item>
      <el-form-item label="头像">
        <el-upload class="avatar-uploader"
                   :show-file-list="false"
                   :before-upload="beforeAvatarUpload">
          <img v-if="curedit.avatar"
               :src="curedit.avatar"
               class="avatar" />
          <el-icon v-else
                   class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="个人介绍">
        <el-input v-model="curedit.introduction"
                  :rows="2"
                  type="textarea"
                  placeholder="Please input" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary"
                   @click="submitform">确认修改</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, watch } from 'vue'
import {
  deleteoneapi,
  getallusersapi,
  oneuser,
  updateuserapi,
} from '@/apis/user'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { uploadapi } from '@/apis/upload'
import { useRouter } from 'vue-router'
import { debounce } from '@/utils'

export default defineComponent({
  name: 'v-usenam',
  setup() {
    const router = useRouter()
    const users = ref<oneuser[]>() //用户数据
    const start = ref<number>(1) //分页数据
    const total = ref<number>(0) //总数
    const dialogTableVisible = ref<boolean>(false) //编辑对话框是否显示
    let curedit = ref<oneuser>({
      username: '',
      avatar: '',
      sex: 0,
      birthday: '',
      introduction: '',
      id: 0,
    }) //当前编辑的用户的信息
    const searchinput = ref<string>('') //搜索内容

    //搜索用户
    watch(
      searchinput,
      debounce(() => {
        getalluserfn()
      })
    )

    //获取所有用户信息
    const getalluserfn = async () => {
      try {
        console.log(searchinput.value)
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const res: any = await getallusersapi(
          (start.value - 1) * 6,
          6,
          searchinput.value
        )
        users.value = res.result
        total.value = res.allcount
      } catch (e) {
        ElMessage.error('身份失效')
        router.push('/login')
      }
    }
    watch(start, () => {
      getalluserfn()
    })
    onMounted(() => {
      getalluserfn()
    })

    const beforeAvatarUpload: UploadProps['beforeUpload'] = async (rawFile) => {
      if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
      }
      const formdata: FormData = new FormData()
      formdata.set('picture', rawFile)
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const re: any = await uploadapi(formdata)
      curedit.value.avatar = re.result
      return true
    }
    //打开编辑用户表单
    const handleEdit = (user: oneuser) => {
      dialogTableVisible.value = true
      curedit.value = user
    }

    //提交修改用户的表单修改
    const submitform = async () => {
      try {
        await updateuserapi(curedit.value)
        getalluserfn()
        ElMessage.success('修改用户成功')
      } catch (e) {
        ElMessage.error('身份失效')
        router.push('/login')
      }
      dialogTableVisible.value = false
    }
    //删除用户
    const handleDelete = async (user: oneuser) => {
      try {
        await deleteoneapi(user.id)
        ElMessage.success('删除用户成功')
        getalluserfn()
      } catch (e) {
        ElMessage.error('身份失效')
        router.push('/login')
      }
    }
    return {
      users,
      total,
      start,
      handleEdit,
      handleDelete,
      dialogTableVisible,
      curedit,
      beforeAvatarUpload,
      Search,
      submitform,
      searchinput,
    }
  },
})
</script>

<style scoped lang="less">
:deep(.avatar-uploader) {
  img {
    width: 60px;
    height: 60px;
  }
}
</style>